package org.gbif.metrics.cli;

import java.io.IOException;

import javax.validation.constraints.NotNull;

import com.beust.jcommander.Parameter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.base.Objects;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * A configuration class which can be used to get all the details needed to create a connection to RabbitMQ.
 * <p/>
 * It provides a convenience method ({@link #getConnection()} to actually get a {@link Connection} object when populated
 * fully.
 */
@SuppressWarnings("PublicField")
class MessagingConfiguration {

  @Parameter(names = "--messaging-host")
  @NotNull
  public String host;

  @Parameter(names = "--messaging-virtual-host")
  @NotNull
  public String virtualHost;

  @Parameter(names = "--messaging-username")
  @NotNull
  public String username;

  @Parameter(names = "--messaging-password", password = true)
  @NotNull
  public String password;

  /**
   * This method returns a connection object to RabbitMQ with the provided settings. These settings are not validated in
   * this method so only call it when the object has been validated.
   * 
   * @return connection to RabbitMQ
   * @throws IOException if connection fails
   */
  @JsonIgnore
  public Connection getConnection() throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(username);
    factory.setPassword(password);
    factory.setVirtualHost(virtualHost);
    factory.setHost(host);
    return factory.newConnection();
  }

  @Override
  public String toString() {
    return Objects.toStringHelper(this).add("host", host).add("virtualHost", virtualHost).add("username", username)
      .add("password", password).toString();
  }
}
